/*
 * Copyright (c) [2019] [Peking University]
 * [BDWare-DOIP] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 *
 *   http://license.coscl.org.cn/MulanPSL
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */
package bdware.doip.server;

import bdware.netty.codec.doip.DoipUDPCodec;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

public class DoipUDPServer {
    private final int port;

    public DoipUDPServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        start(1718);
    }

    private static void start(int port) {
        new DoipUDPServer(port).start();
    }

    private void start() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        try {
            Bootstrap b = new Bootstrap();
            b.group(bossGroup)
                    .channel(NioDatagramChannel.class)
                    .localAddress(port)
                    .option(ChannelOption.SO_BROADCAST, true);
            b.handler(
                    new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        protected void initChannel(NioDatagramChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new DoipUDPCodec())
                                     .addLast(new DoipServerHandler());
                        }
                    });
            Channel ch = b.bind().syncUninterruptibly().channel();
            System.out.println("[DoipUDPServer] start at:" + port);
            ch.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
        }
    }
}
